#!/bin/bash

# 简化的快速更新脚本
set -e

echo "🔄 Web3管理平台 - 快速更新"
echo "=========================="

# 检查Docker容器状态
check_status() {
    echo "📊 检查当前状态..."
    docker-compose ps
    echo ""
}

# 执行SQL更新
execute_sql_updates() {
    echo "📊 检查并执行SQL更新..."

    # SQL文件目录和顺序
    SQL_FILES=(
        "init.sql"
        "upgrade_v1.3.sql"
        "backend/add_restart_fields.sql"
    )

    # 检查数据库连接
    if ! docker exec web3-mysql mysql -u root -p123456 -e "USE web3_management; SELECT 1;" >/dev/null 2>&1; then
        echo "❌ 数据库连接失败，跳过SQL更新"
        return 1
    fi

    # 创建version_history表（如果不存在）
    docker exec web3-mysql mysql -u root -p123456 web3_management << 'EOF' 2>/dev/null || true
CREATE TABLE IF NOT EXISTS version_history (
    id INT AUTO_INCREMENT PRIMARY KEY,
    script_name VARCHAR(255) NOT NULL UNIQUE,
    executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    checksum VARCHAR(64),
    INDEX idx_script_name (script_name)
);
EOF

    # 执行SQL文件
    for sql_file in "${SQL_FILES[@]}"; do
        if [ -f "$sql_file" ]; then
            echo "🔍 检查 $sql_file..."

            # 计算文件校验和
            if command -v md5sum >/dev/null 2>&1; then
                checksum=$(md5sum "$sql_file" | cut -d' ' -f1)
            elif command -v md5 >/dev/null 2>&1; then
                checksum=$(md5 -q "$sql_file")
            else
                checksum="unknown"
            fi

            # 检查是否已执行过
            executed=$(docker exec web3-mysql mysql -u root -p123456 web3_management -se "SELECT COUNT(*) FROM version_history WHERE script_name='$sql_file' AND checksum='$checksum';" 2>/dev/null || echo "0")

            if [ "$executed" -eq "0" ]; then
                echo "⚡ 执行 $sql_file..."
                if docker exec -i web3-mysql mysql -u root -p123456 web3_management < "$sql_file" 2>/dev/null; then
                    # 记录执行历史
                    docker exec web3-mysql mysql -u root -p123456 web3_management -e "INSERT INTO version_history (script_name, checksum) VALUES ('$sql_file', '$checksum') ON DUPLICATE KEY UPDATE executed_at=CURRENT_TIMESTAMP, checksum='$checksum';" 2>/dev/null || true
                    echo "✅ $sql_file 执行成功"
                else
                    echo "⚠️  $sql_file 执行失败，继续..."
                fi
            else
                echo "⏭️  $sql_file 已执行过，跳过"
            fi
        else
            echo "⚠️  文件不存在: $sql_file"
        fi
    done

    echo "✅ SQL更新检查完成"
}

# 简单更新
simple_update() {
    echo "⚡ 执行快速更新..."

    # 1. 拉取最新代码
    echo "📥 拉取最新代码..."
    git pull || echo "⚠️  Git更新失败，继续..."

    # 2. 检查并更新前端依赖
    echo "📦 检查前端依赖更新..."
    if [ -f "frontend/package.json" ]; then
        # 检查是否需要更新依赖（比较package.json修改时间）
        if [ "frontend/package.json" -nt "frontend/package-lock.json" ] 2>/dev/null || [ ! -f "frontend/package-lock.json" ]; then
            echo "🔄 检测到package.json更新，重新安装依赖..."
            cd frontend
            rm -f package-lock.json
            npm install --silent
            cd ..
            echo "✅ 前端依赖更新完成"
        else
            echo "⏭️  前端依赖无需更新"
        fi
    fi

    # 3. 执行SQL更新
    execute_sql_updates

    # 4. 重新构建和启动
    echo "🔧 重新构建镜像..."
    docker-compose build --no-cache

    echo "🚀 重启服务..."
    docker-compose down
    docker-compose up -d

    echo "✅ 更新完成！"
}

# 查看日志
show_logs() {
    echo "📋 显示服务日志..."
    docker-compose logs --tail=50
}

# 快速备份
quick_backup() {
    echo "💾 创建快速备份..."
    backup_dir="backup-$(date +%Y%m%d_%H%M%S)"
    mkdir -p $backup_dir

    # 备份数据库
    docker exec web3-mysql mysqldump -u root -p123456 web3_management > $backup_dir/database.sql 2>/dev/null || echo "⚠️  数据库备份失败"

    # 备份配置
    cp .env $backup_dir/ 2>/dev/null || echo "⚠️  配置备份失败"

    echo "✅ 备份完成: $backup_dir"
}

# 主菜单
show_menu() {
    echo ""
    echo "请选择操作："
    echo "1) 检查状态"
    echo "2) 快速更新"
    echo "3) 查看日志"
    echo "4) 创建备份"
    echo "5) 重启服务"
    echo "6) 仅执行SQL更新"
    echo "0) 退出"
    echo ""
}

# 主函数
main() {
    case ${1:-menu} in
        --update)
            simple_update
            ;;
        --status)
            check_status
            ;;
        --logs)
            show_logs
            ;;
        --backup)
            quick_backup
            ;;
        --sql-update)
            execute_sql_updates
            ;;
        *)
            while true; do
                show_menu
                read -p "请输入选择 (0-6): " choice
                case $choice in
                    1) check_status ;;
                    2) simple_update ;;
                    3) show_logs ;;
                    4) quick_backup ;;
                    5)
                        echo "🔄 重启服务..."
                        docker-compose restart
                        echo "✅ 重启完成"
                        ;;
                    6) execute_sql_updates ;;
                    0) exit 0 ;;
                    *) echo "❌ 无效选择" ;;
                esac
                echo ""
                read -p "按Enter继续..."
                clear
            done
            ;;
    esac
}

# 错误处理
trap 'echo "❌ 操作失败"; exit 1' ERR

# 执行主程序
main "$@"